package com.example.worklab.pathmeasure.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PathMeasure
import android.view.View
import android.view.animation.LinearInterpolator
import com.example.worklab.R

class PlaneLoadingView @JvmOverloads constructor(
    context: Context,
    attrs: android.util.AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val mCirclePaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        setColor(Color.RED)
        strokeWidth = 2f
    }
    private val mCirclePath: Path = Path().apply {
        addCircle(0f, 0f, 200f, Path.Direction.CW)
    }

    private val mArrowBitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.arrow)

    // 坐标数据
    private val mPos = FloatArray(2)

    //正余弦数组
    private val mTan = FloatArray(2)

    private var mCurrentValue = 0F

    private val valueAnimator: ValueAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
        duration = 5000
        interpolator = LinearInterpolator()
        repeatCount = ValueAnimator.INFINITE
        addUpdateListener {
            mCurrentValue = it.animatedValue as Float
            invalidate()
        }
    }

    private val matrix: Matrix = Matrix()
    private var mPathMeasure: PathMeasure = PathMeasure(mCirclePath, false)

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.translate(width * 1.0f / 2, height * 1.0f / 2)
        //绘制圆形
        canvas.drawPath(mCirclePath, mCirclePaint)

        mPathMeasure.getPosTan(mPathMeasure.length * mCurrentValue, mPos, mTan)

        //计算角度
        val degree = (Math.atan2(mTan[1].toDouble(), mTan[0].toDouble()) * 180 / Math.PI).toFloat()
        matrix.reset()
        matrix.postRotate(degree, mArrowBitmap.width * 1.0f / 2, mArrowBitmap.height * 1.0f / 2)
        matrix.postTranslate(
            mPos[0] - mArrowBitmap.width * 1.0f / 2,
            mPos[1] - mArrowBitmap.height * 1.0f / 2
        )

        canvas.drawCircle(0f, 0f, 3f, mCirclePaint)
        canvas.drawBitmap(mArrowBitmap, matrix, mCirclePaint)
        canvas.drawCircle(mPos[0], mPos[1], 3f, mCirclePaint)

    }

    fun start() {
        if (valueAnimator.isRunning) {
            return
        }
        valueAnimator.start()
    }

    fun stop() {
        valueAnimator.cancel()
    }

}